﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace JQueryWidget.WidgetFrame.Common
{
    public class TemplatePage : System.Web.UI.Page, ITemplatePage
    {
        public int PageID
        {
            get;
            set;
        }

        public IWidgetStoreTemplate LoadWidgetStoreTemplate()
        {
            if (PageID > 0)
            {
                var templatedataid = (from pageEle in XDocument.Load(Server.MapPath("~/Data/pagedata.xml")).Elements("pages").Elements("page")
                               where pageEle.Element("id").Value == PageID.ToString()
                               select pageEle.Element("templatedataid").Value).FirstOrDefault();
                if (templatedataid != null)
                {
                    var templateid = (from templatedata in XDocument.Load(Server.MapPath("~/Data/templatedata.xml")).Element("templatedatas").Elements("templatedata")
                                          where templatedata.Element("id").Value == templatedataid
                                          select templatedata.Element("templateid").Value).FirstOrDefault();
                    if (templateid != null)
                    {
                        var templateSrc = (from template in XDocument.Load(Server.MapPath("~/Data/templates.xml")).Element("templates").Elements("template")
                                           where template.Element("id").Value == templateid
                                           select template.Element("src").Value).FirstOrDefault();
                        if (templateSrc != null)
                        {
                            IWidgetStoreTemplate widgetStoreTemplate = Page.LoadControl(templateSrc) as IWidgetStoreTemplate;
                            widgetStoreTemplate.TemplateDataID = Convert.ToInt32(templatedataid);
                            widgetStoreTemplate.NeedWrapper = NeedWrapper;
                            widgetStoreTemplate.LoadColumns();
                            return widgetStoreTemplate;
                        }
                    }
                }
            }
            return null;
        }


        public bool NeedWrapper
        {
            get;
            set;
        }
    }
}